package com.service.user.impl;

import com.dao.GoodsDao;
import com.dao.OrderDao;
import com.entity.Goods;
import com.entity.Notice;
import com.entity.Order;
import com.service.user.GoodService;
import com.service.user.NoticeService;
import com.service.user.OrderService;
import com.service.user.SellerService;
import com.utils.FileUploadUtil;
import com.utils.SqlSessionGetter;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 提供所有卖家页所需的服务
 *
 * 
 */
@Service
public class SellerServiceImpl implements SellerService {

  @Autowired GoodService goodService;
  @Autowired NoticeService noticeService;
  @Autowired OrderService orderService;

  /**
   * 添加商品
   *
   * @param userId 用户名
   * @param name 书名 不为空
   * @param file 封面图片（只能是jpg/jpeg/png/gif格式的图片文件) 不为空
   * @param price 价格 不为空
   * @param appearance 品相 不为空
   * @param ISBN ISBN码
   * @param categoryId 类别编号，不为空
   * @param author 作者
   * @param translator 译者
   * @param version 版本号
   * @param store 库存
   * @param freight 邮费，不为空
   * @param pressHorse 出版社
   * @param publicationDate 出版日期
   * @param describe 商品描述
   * @param status 商品状态（1为直接上架，0为不上架)
   * @return 添加成功返回书籍编号和书籍封面图片url，否则返回null
   */
  @Override
  public Map<String, String> addAGoods(
      String userId,
      String name,
      MultipartFile file,
      float price,
      String appearance,
      String ISBN,
      int categoryId,
      String author,
      String translator,
      String version,
      int store,
      float freight,
      String pressHorse,
      Date publicationDate,
      String describe,
      int status) {
    // 随机生成商品id
    String goodId = UUID.randomUUID().toString().replace("-", "");
    // 保存商品图片到本地，并得到访问URL
    String imageURL =
        FileUploadUtil.uploadFile(
            file, goodId, FileUploadUtil.GOODS_IMAGES_SUBDIR, FileUploadUtil.IMAGE_SUFFIX);

    if (imageURL == null) {
      // 文件类型错误,不允许没有封面图片的商品
      return null;
    }

    SqlSession session = SqlSessionGetter.getSqlSession();
    GoodsDao dao = session.getMapper(GoodsDao.class);
    try {
      dao.insertGood(
          userId,
          goodId,
          name,
          imageURL,
          price,
          appearance,
          ISBN,
          categoryId,
          author,
          translator,
          version,
          store,
          freight,
          pressHorse,
          publicationDate,
          describe,
          status);
      session.commit();
    } catch (Exception exp) {
      // 插入失败时删除图片
      FileUploadUtil.delFile(imageURL);
      System.out.println("商品添加失败");
      session.close();
      return null;
    }
    session.close();

    // 返回添加商品的id和图片URL
    HashMap<String, String> idUrl = new HashMap<>(2);
    idUrl.put("goodId", goodId);
    idUrl.put("imageURL", imageURL);
    return idUrl;
  }

  /**
   * 添加商品更多图片或视频描述，每个商品最多允许添加5个描述，单个描述不超过20MB
   *
   * @param userId 用户编号
   * @param goodId 商品编号
   * @param files 文件列表(只能是图片或视频）
   * @return 添加成功文件的url列表
   */
  @Override
  public List<String> addGoodsMoreFiles(String userId, String goodId, MultipartFile[] files) {
    // 将路径保存
    SqlSession session = SqlSessionGetter.getSqlSession();
    GoodsDao dao = session.getMapper(GoodsDao.class);
    // 该商品已有文件数
    int has = dao.selectGoodMoreFileCount(goodId);
    // 该商品还可存入文件数
    int rest = FileUploadUtil.MORE_FILE_MAX_COUNT - has;
    if (rest <= 0) {
      // 文件数量已经达到限制
      return null;
    }
    // 保存图片URL
    ArrayList<String> filesURL = new ArrayList<>(Math.min(files.length, rest));
    // 上传文件，获得url
    String fileName, fileURL;
    for (MultipartFile file : files) {
      if (rest <= 0) {
        break;
      }
      fileName = UUID.randomUUID().toString().replace("-", "");
      fileURL =
          FileUploadUtil.uploadFile(
              file, fileName, FileUploadUtil.GOODS_MORE_SUBDIR, FileUploadUtil.GOODS_MORE_SUFFIX);
      if (fileURL != null) {
        filesURL.add(fileURL);
        rest--;
      }
    }

    if (filesURL.size() > 0) {
      // url存入数据库
      dao.insertMoreFilesURL(goodId, filesURL);
      session.commit();
      session.close();
    }
    return filesURL;
  }

  @Override
  public int getMyGoodCount(String userId, int goodStatus) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    GoodsDao dao = session.getMapper(GoodsDao.class);
    int count = dao.selectSellerGoodCount(userId, goodStatus);
    session.close();
    return count;
  }

  /**
   * 获取卖家自己的商品
   *
   * @param userId 用户编号
   * @param goodsStatus 商品状态
   * @param pageSize 页大小
   * @param pageIndex 页索引
   * @return 卖家的对应状态的对应页的商品列表
   */
  @Override
  public List<Goods> getMyGoods(String userId, int goodsStatus, int pageSize, int pageIndex) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    GoodsDao dao = session.getMapper(GoodsDao.class);
    List<Goods> goods = dao.selectSellerGoods(userId, goodsStatus, pageIndex * pageSize, pageSize);

    session.close();
    return goods;
  }

  @Override
  public Goods getMyGoodDetail(String userId, String goodId) {
    return goodService.getGoodDetail(userId, goodId, -1);
  }

  @Override
  public int chGoodInfo(
      String userId,
      String goodId,
      String name,
      float price,
      String appearance,
      String ISBN,
      int categoryId,
      String author,
      String translator,
      String version,
      int store,
      float freight,
      String pressHorse,
      Date publicationDate,
      String describe) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    GoodsDao dao = session.getMapper(GoodsDao.class);
    int ret =
        dao.updateGoodInfo(
            userId,
            goodId,
            name,
            price,
            appearance,
            ISBN,
            categoryId,
            author,
            translator,
            version,
            store,
            freight,
            pressHorse,
            publicationDate,
            describe);
    session.commit();
    session.close();
    return ret;
  }

  /**
   * 修改商品封面图片
   *
   * @param userId 用户编号
   * @param goodId 商品编号
   * @param file 图片文件
   * @return 修改成功返回url,失败返回null
   */
  @Override
  public String chGoodCoverImage(String userId, String goodId, MultipartFile file) {
    String newImageURL =
        FileUploadUtil.uploadFile(
            file,
            UUID.randomUUID().toString().replace("-", ""),
            FileUploadUtil.GOODS_IMAGES_SUBDIR,
            FileUploadUtil.IMAGE_SUFFIX);

    if (newImageURL == null) {
      // 文件类型错误或上传
      return null;
    }

    SqlSession session = SqlSessionGetter.getSqlSession();
    GoodsDao dao = session.getMapper(GoodsDao.class);
    // 取得原来图片的地址
    String oldImageURL = dao.selectGoodImageURL(goodId);
    // 将原来的图片删除
    FileUploadUtil.delFile(oldImageURL);

    // 保存新的url
    dao.updateGoodImageURL(userId, goodId, newImageURL);
    session.commit();
    session.close();
    return newImageURL;
  }

  @Override
  public int delGoodMoreFile(String userId, String goodId, String fileURL) {
    return goodService.delGoodMoreFile(userId, goodId, fileURL);
  }

  @Override
  public int putOnGood(String userId, String goodId) {
    return goodService.chGoodStatus(userId, goodId, GoodsDao.ON_SHELVE);
  }

  @Override
  public int putOffGood(String userId, String goodId) {
    return goodService.chGoodStatus(userId, goodId, GoodsDao.NORMAL_OFF_SHELVE);
  }

  @Override
  public int delGood(String userId, String goodId) {
    return goodService.delGood(userId, goodId);
  }

  @Override
  public int getSellOrderCount(String userId, int orderStatus) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    OrderDao dao = session.getMapper(OrderDao.class);
    int count = dao.selectBuyerOrSellerOrderCount(userId, orderStatus, true);
    session.close();
    return count;
  }

  /**
   * 获取卖书订单
   *
   * @param userId 用户编号
   * @param orderStatus 订单状态
   * @param pageSize 页大小
   * @param pageIndex 页索引
   * @return 该用户对应页对应状态的卖书订单列表
   */
  @Override
  public List<Order> getMyOrders(String userId, int orderStatus, int pageSize, int pageIndex) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    OrderDao dao = session.getMapper(OrderDao.class);
    List<Order> orders =
        dao.selectBuyerOrSellerOrders(userId, orderStatus, pageIndex * pageSize, pageSize, true);
    session.close();
    return orders;
  }

  /**
   * 确认发货
   *
   * @param orderId 订单编号
   * @return 确认成功返回1，否则返回0
   */
  @Override
  public int confirmDelivery(String orderId, String courierCompany, String courierNumber) {
    SqlSession session = SqlSessionGetter.getSqlSession();
    OrderDao dao = session.getMapper(OrderDao.class);
    int row = dao.updateDeliveryInfo(orderId, courierCompany, courierNumber);
    session.commit();
    session.close();

    Order order = orderService.getOrdersByIds(Arrays.asList(orderId)).get(0);

    // 添加买家通知
    if (courierCompany == null) {
      // 线下
      noticeService.addNotice(
          order.getBuyer().getId(),
          Notice.CONFIRM_GOODS_OFFLINE,
          null,
          0,
          orderId,
          order.getGood().getName());
    } else {
      // 线上
      noticeService.addNotice(
          order.getBuyer().getId(),
          Notice.START_DELIVERY,
          null,
          0,
          orderId,
          order.getGood().getName(),
          courierCompany,
          courierNumber);
    }
    return row;
  }
}
